using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DynamicExcelImportWebControl
{
    [DefaultProperty("Options"), ParseChildren(true, "Options")]
    public class DropDownListColumn : BaseGridColumn
    {
        private ListItemCollection _optionsList;
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public ListItemCollection Options
        {
            get { return _optionsList; }
            set { _optionsList = value; }
        }


        public DropDownListColumn()
        {
            this.Options = new ListItemCollection();
            this.ClientClassName = "DropDownListColumn";
        }

        public DropDownListColumn(string Name)
            : this()
        {
            this.HeaderName = Name;
        }

        public override string RenderInitScript(string Template)
        {
            string optionsArrayId = string.Concat("options", this.Id.ToString("N"));
            StringBuilder result = new StringBuilder();
            result.AppendFormat("var {0} = new Array();", optionsArrayId);
            result.AppendLine();
            for (int i = 0; i < this.Options.Count; i++)
            {
                result.AppendFormat("{0}[{1}] = new Option('{2}', '{3}');", 
                    optionsArrayId,
                    i.ToString(),
                    this.Options[i].Text,
                    this.Options[i].Value,
                    this.Options[i].Selected.ToString().ToLower()
                );
                result.AppendLine();

                if (this.Options[i].Selected)
                {
                    result.AppendFormat("{0}[{1}].selected = {2};",
                        optionsArrayId,
                        i.ToString(),
                        this.Options[i].Selected.ToString().ToLower()
                    );
                    result.AppendLine();
                    result.AppendFormat("{0}[{1}].defaultSelected = {2};",
                        optionsArrayId,
                        i.ToString(),
                        this.Options[i].Selected.ToString().ToLower()
                    );
                    result.AppendLine();
                }
            }
            string init = string.Concat("new ", this.ClientClassName, "('", this.HeaderName, "', ", optionsArrayId, ")");
            result.AppendFormat(Template, init);

            return result.ToString();
        }

    }
}
